﻿using B.S.BasicData.Api.Read.Applications.Commands.Accounts;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastcuture.Commons;
using B.S.BasicData.Infrastcuture.Interfaces;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore.Update;

namespace B.S.BasicData.Api.Read.Applications.CommandHandlers.Accounts
{
    /// <summary>
    /// 登录参数
    /// </summary>
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, ApiResult<LoginDto>>
    {

        private readonly IBaseRepository<UserInfo> userbaseRepository;
        private readonly IBaseRepository<Role> rolebaseRepository;

        public LoginQueryCommandHandler(IBaseRepository<UserInfo> userbaseRepository, IBaseRepository<Role> rolebaseRepository)
        {
            this.userbaseRepository = userbaseRepository;
            this.rolebaseRepository = rolebaseRepository;
        }


        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<LoginDto>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<LoginDto> result = new ApiResult<LoginDto>();
            result.Code = ResultCode.LoginSuccess;
            result.Message = ResultCode.LoginSuccess.Description();
            var list = from a in userbaseRepository.GetAll()
                       join b in rolebaseRepository.GetAll()
                       on a.RoleId equals b.RoleId
                       where a.UserName==request.UserName
                       select new LoginDto
                       {
                           UserName=a.UserName,
                           UserPwd=a.UserPwd,
                           NickName=a.NickName,
                           IsDelete=a.IsDelete,
                           RoleName=b.RoleName,
                       };
            var user = list.FirstOrDefault();
            if(user==null)
            {
                result.Code = ResultCode.LoginFail;
                result.Message = ResultCode.LoginFail.Description() + "用户名不存在";
                return Task.FromResult(result);
            }
            request.UserPwd =request.UserPwd.GetMD5();
            if (user.UserPwd!=request.UserPwd)
            {
                result.Code = ResultCode.LoginFail;
                result.Message = ResultCode.LoginFail.Description() + "密码错误";
                return Task.FromResult(result);
            }
            if(user.IsDelete==1)
            {
                result.Code = ResultCode.LoginFail;
                result.Message = ResultCode.LoginFail.Description() + "用户被禁用";
                return Task.FromResult(result);
            }
            result.Data = user;
            return Task.FromResult(result);

        }
    }
}
